package com.sl.diary.component;

import com.sl.diary.R;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;

public class ListPopup extends PopupWindow {

	private View popup_view;
	private Context context;
	private PopupItemAdapterEventCallback callback;

	public ListPopup(Context context) {
		super(context);
		this.context = context;

		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(context.LAYOUT_INFLATER_SERVICE);
		popup_view = layoutInflater.inflate(R.layout.layout_popup_shop_map_type,
				null);
		setContentView(popup_view);
		setHeight(LayoutParams.WRAP_CONTENT);
		setWidth(LayoutParams.WRAP_CONTENT);
		// set popup's properties
		setTouchable(true);
		setFocusable(true);
		setOutsideTouchable(true);
		setBackgroundDrawable(new BitmapDrawable());
		setTouchInterceptor(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
					dismiss();
					return true;
				}
				return false;
			}
		});

	}

	public void setData(String[] data, PopupItemAdapterEventCallback callback) {
		this.callback = callback;
		// set data for list
		ListView list = (ListView) popup_view.findViewById(R.id.list_show);
		list.setAdapter(new ArrayAdapter<String>(context,
				R.layout.layout_popup_item, R.id.txt_item, data));
		list.setOnItemClickListener(onPopupListItemClick);
	}

	OnItemClickListener onPopupListItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (callback != null) {
				callback.onSelectPopupItem(position);
			}
		}
	};

	/**
	 * @interface PopupItemAdapterEventCallback - call back to activity to
	 *            handle click item event
	 */
	public interface PopupItemAdapterEventCallback {

		public void onSelectPopupItem(int position);
	}

}
